<template>
  <div>
    <basic-container>
      <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
          <el-form-item label="角色名称" prop="role">
            <el-input v-model="queryParams.menuName" placeholder="请输入角色名称" clearable @clear="getList" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-col>
          <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
        </el-row>
        <el-table v-if="refreshTable" v-loading="loading" :data="menuList" row-key="menuId"
          :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
          <el-table-column prop="role" label="角色名称" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="describe" label="角色描述" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.describe }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="perms" label="权限标识" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ getLabelsWithAllow(scope.row.sidebars).join(', ') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" :disabled="scope.row.role == 'admin'"
                @click="handleUpdate(scope.row)">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" :disabled="scope.row.role == 'admin'"
                @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.index" :limit.sync="queryParams.size"
          @pagination="getList" />
        <!-- 添加或修改菜单对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body :close-on-click-modal="false">
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-row>
              <el-col :span="16">
                <el-form-item label="角色名称" prop="role">
                  <el-input v-model="form.role" placeholder="请输入角色名称" />
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item label="角色描述" prop="describe">
                  <el-input v-model="form.describe" placeholder="请输入角色描述" />
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item label="页面权限">
                  <div class="block">
                    <el-cascader v-model="form.sidebars" :options="menu" :props="propObj" clearable
                      style="width: 100%"></el-cascader>
                  </div>

                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </div>
    </basic-container>
  </div>
</template>

<script>
import { addRoles, getMenu, eidtRoles, dletRoles } from "@/api/RoleEditing";
import { mapGetters } from "vuex";

export default {

  data() {
    return {
      // 遮罩层
      propObj: {
        multiple: true,
        value: 'mark',
        label: 'label',
        children: 'children'
      },
      loading: false,
      // 显示搜索条件
      showSearch: true,
      value1: [],
      total: 1,
      inMess: [],
      menuList: [],
      options: [{
        value: '1',
        label: '生效中'
      }, {
        value: '2',
        label: '禁用'
      }, {
        value: '3',
        label: '审核中'
      }],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部折叠
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        index: 1,
        menuName: '',
        size: 10,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        role: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ],
        describe: [
          { required: true, message: "角色描述不能为空", trigger: "blur" }
        ],
      }
    }

  },
  created() {
    this.getList();

  },
  computed: {
    ...mapGetters(["userInfo", "menu"]),
  },

  methods: {
    getLabelsWithAllow(sidebar) {
      return sidebar
        .filter(item => item.allow)
        .map(item => item.label);
    },
    /** 查询菜单列表 */
    getList() {
      this.loading = true;
      getMenu(this.queryParams).then(response => {
        this.menuList = response.data.data
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        role: '',
        describe: "",
        sidebars: [],
      };

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.menuList = this.menuList.filter(item => {
        return item.role.toLowerCase().includes(this.queryParams.menuName.toLowerCase());
      });

    },
    /** 重置按钮操作 */
    resetQuery() {
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.reset()
      this.title = "添加角色";
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form.sidebars = []
      row.sidebars.forEach((sidebar) => {
        sidebar.children
          .filter((child) => child.allow)
          .forEach((child) => {
            this.form.sidebars.push([sidebar.mark, child.mark]);
          });
      });

      this.open = true;
      this.title = "角色修改";
      this.form.role = row.role
      this.form.role_id = row.role_id
      this.form.describe = row.describe
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let menuData = JSON.parse(JSON.stringify(this.menu));
          menuData.forEach(item => {
            item.allow = false;
            item.children.forEach(childItem => {
              childItem.allow = false;
            });
          });
          let lastItems = [];
          this.form.sidebars.forEach(item => {
            if (item.length > 0) {
              lastItems.push(item[item.length - 1]);
            }
          });
          menuData.forEach(item => {
            item.children.forEach(child => {
              if (lastItems.includes(child.mark)) {
                child.allow = true;
              }
            });
          });
          this.form.sidebars = menuData
          if (!this.form.role_id) {
            addRoles(this.form).then(res => {
              console.log(res);
              this.$message({
                message: '添加成功',
                type: 'success'
              });
              this.open = false;
              this.getList();
            })
          } else {
            eidtRoles(this.form).then(res => {
              console.log(res);
              this.$message({
                message: '修改成功',
                type: 'success'
              });
              this.open = false;
              this.getList();
            })
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除名称为"' + row.role + '"的角色？').then(function () {
        return dletRoles({ role_id: row.role_id });
      }).then((res) => {
        if (res.data.status !== 200) {
          let mes = res.data.msg
          this.$message({
            message: mes,
            type: 'error'
          });
        } else {
          this.$message({
            message: "删除成功",
            type: 'success'
          });
        }
        this.getList();
      }).catch(() => { });
    }
  }
};
</script>

<style></style>